<script setup lang="ts">
import { Form } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, watch, ref, onBeforeUnmount } from 'vue'
import { CurdData } from '@/api/logisticsRules/types'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
import { useValidator } from '@/hooks/web/useValidator'
import { getFieldEnumApi } from '@/api/logisticsRules'
import { FieldEnum } from '@/api/logisticsRules/types'
import { SchemaConfig } from '@/api/global/types'
import useSchema from './hooks/useSchema'
import { useI18n } from '@/hooks/web/useI18n'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { SelectedItem, useTableDialogStore } from '@/store/modules/tableDialog'
import { getListApi } from '@/api/product'
import { TableDialog } from '@/components/Dialog'

const { t } = useI18n()
const { required } = useValidator()

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<CurdData>>,
    default: () => null
  }
})

// 调用 useProductSchema 函数以获取实际的 Product CrudSchema[]
// const productCurdSchema = useProductSchema()

const productTableDialogStoreID = 'customerContactWrite'
const productTableDialogStore = useTableDialogStore(productTableDialogStoreID)
const productTableDialogSelectedLimit = 1
const productItemTitleName = 'cname'

const productCurdSchema = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('product.id'),
    align: 'center',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'cname',
    label: t('product.cname'),
    form: {
      component: 'Input',
      formItemProps: {
        rules: [required()]
      },
      colProps: {
        span: 24
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },

  {
    field: 'sku',
    label: t('product.sku'),
    form: {
      component: 'Input',
      formItemProps: {
        rules: [required()]
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'code',
    label: t('product.code'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      formItemProps: {
        rules: [required()]
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'style_code',
    label: t('product.style_code'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      formItemProps: {
        rules: [required()]
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'category',
    label: t('product.category'),
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        // options: categoryList
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.category_value
        }
      }
    }
  },
  {
    field: 'brand',
    label: t('product.brand'),
    form: {
      component: 'Select',
      componentProps: {
        // options: brandList
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.brand_value
        }
      }
    }
  },
  {
    field: 'color_specs',
    label: t('product.color_specs'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'condition',
    label: t('product.condition'),
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: t('product.conditionValue.1'),
            value: '1'
          },
          {
            label: t('product.conditionValue.0'),
            value: '0'
          }
        ]
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center',
      slots: {
        default: (data: any) => {
          return data.row.condition_text
        }
      }
    }
  },
  {
    field: 'expiration_date',
    label: t('product.expiration_date'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'currency',
    label: t('product.currency'),
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        // options: currencyList,
        multiple: true
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'hashrate',
    label: t('product.hashrate'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'computing_unit',
    label: t('product.computing_unit'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'power',
    label: t('product.power'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'weight',
    label: t('product.weight'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'gross_weight',
    label: t('product.gross_weight'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'transport_weight',
    label: t('product.transport_weight'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'dimensions',
    label: t('product.dimensions'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'gross_dimensions',
    label: t('product.gross_dimensions'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'volume',
    label: t('product.volume'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'freight_tag',
    label: t('product.freight_tag'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'model',
    label: t('product.model'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'describe',
    label: t('product.describe'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'remark',
    label: t('product.remark'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'min_num',
    label: t('product.min_num'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'number',
        value: 0
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'cost',
    label: t('product.cost'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'number'
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'sales_rate',
    label: t('product.sales_rate'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'number'
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'unit_price',
    label: t('product.unit_price'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'number'
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'sales_price',
    label: t('product.sales_price'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'number'
      },
      formItemProps: {
        rules: [required()]
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'freight_price',
    label: t('product.freight_price'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input',
      componentProps: {
        type: 'number'
      }
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  }
])
const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose, setSchema } = formMethods

// Begin CRUD Template Block
// ------------------------
const allSchemas = ref<AllSchemas>({
  formSchema: [] // 确保与接口匹配
})
const fieldEnum = ref<FieldEnum>({}) // 根据实际数据初始化
getFieldEnumApi({ field: 'all' })
  .then((res) => {
    fieldEnum.value = res.data

    const schemaConfig: SchemaConfig = {
      actionButtonsTemplate: undefined,
      fieldEnum: fieldEnum.value,
      tableDialogCurdSchema: productCurdSchema,
      tableDialogStoreID: productTableDialogStoreID
    }

    // 获取表单配置
    const { crudSchemas } = useSchema(schemaConfig)
    const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

    // 合并新的数据，确保不改变原有数据的类型
    allSchemas.value = {
      formSchema: newSchemas.formSchema || []
    }
  })
  .catch((error) => {
    console.error('API call failed', error)
  })
// End CRUD Template Block
// ------------------------

const rules = reactive({
  // rule_name: [required()],
  // logistics_name: [required()],
  // terms: [required()],
  // content: [required()]
})

const submit = async () => {
  const elForm = await getElFormExpose()
  console.log('data', await getFormData())
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  console.log('valid', valid)
  if (valid) {
    const formData = await getFormData()
    formData.product_id = parseInt(
      productTableDialogStore.selectedItems.map((item) => item.id).join(',')
    )
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
    const selectedItems = ref<SelectedItem[]>([])
    // selectedItems.value = [{ id: currentRow?.product_id, title: currentRow?.product_object.cname }]
    productTableDialogStore.selectedItems = selectedItems.value
    setSchema([
      {
        field: 'content',
        path: 'componentProps.defaultHtml',
        value: currentRow?.notes
      }
    ])
  },
  {
    deep: true,
    immediate: true
  }
)
// 清空 store 数据
onBeforeUnmount(() => {
  productTableDialogStore.reset()
})
defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="allSchemas.formSchema" />

  <TableDialog
    :getListApi="getListApi"
    :limit="productTableDialogSelectedLimit"
    :tableDialogStoreID="productTableDialogStoreID"
    :itemTitleName="productItemTitleName"
  />
</template>
